Popular Searches
Popular Course Categories
Popular Courses

JSX Best Practices

JSX Best Practices

JSX in React

JSX Best Practices in React JS – Detailed Notes

Topic: JSX Best Practices

Course: React JS Training

JSX (JavaScript XML) is a syntax extension used in React that allows developers to write HTML-like markup inside JavaScript code. Following JSX best practices makes React applications easier to read, maintain, debug, reuse, and scale.

React JS Training Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Are JSX Best Practices?

JSX best practices are recommended coding techniques that help developers write clean, consistent, reusable, and error-free JSX code in React applications.

They include using meaningful component names, writing readable markup, keeping components small, using correct JSX attributes, handling lists with unique keys, and avoiding unnecessary complexity.

Example: Poor JSX vs. Better JSX

Poor JSX:

function App(){return <div><h1>welcome</h1><p>learn react</p><button>click</button></div>;}

Better JSX:

function App() {
  return (
    <div>
      <h1>Welcome to React</h1>
      <p>Learn React step by step.</p>
      <button>Get Started</button>
    </div>
  );
}

The second example is easier to understand because the code is properly formatted and the content is meaningful.


2. Use Proper Indentation and Formatting

Always format JSX with consistent indentation and line breaks. Readable code makes it easier to identify nesting errors and understand the UI structure.

Example

function Profile() {
  return (
    <section className="profile">
      <h2>User Profile</h2>
      <p>Welcome to your profile.</p>
    </section>
  );
}

Best practices

  • Use consistent indentation throughout the project.
  • Place nested elements on separate lines when it improves readability.
  • Use parentheses around multiline JSX returned by a function.
  • Avoid putting an entire component on one long line.
  • Use a consistent formatter such as Prettier when available.

3. Use Meaningful Component Names

React component names should describe their purpose. Component names must begin with an uppercase letter so React can distinguish custom components from built-in HTML elements.

Incorrect

function usercard() {
  return <div>User Information</div>;
}

Correct

function UserCard() {
  return (
    <div>
      User Information
    </div>
  );
}

Common naming conventions

Item Recommended style Example
React component PascalCase UserCard
JavaScript variable camelCase userName
Function camelCase handleClick
Constant UPPER_SNAKE_CASE when appropriate MAX_ITEMS
CSS class Consistent project convention user-card

4. Use One Parent Element or a Fragment

A component must return one JSX expression. When you need multiple sibling elements, wrap them in a parent element or use a React Fragment.

Using a parent element

function Welcome() {
  return (
    <div>
      <h1>Hello!</h1>
      <p>Welcome to React.</p>
    </div>
  );
}

Using a Fragment

function Welcome() {
  return (
    <>
      <h1>Hello!</h1>
      <p>Welcome to React.</p>
    </>
  );
}

A Fragment groups elements without adding an extra DOM element. Prefer it when an additional wrapper is not needed for layout, styling, or semantics.


5. Use Correct JSX Attributes

JSX follows JavaScript-oriented naming conventions for many attributes. Some familiar HTML attributes have different names in JSX.

HTML attribute JSX attribute Purpose
class className Assigns a CSS class
for htmlFor Associates a label with a form field
onclick onClick Handles a click event
tabindex tabIndex Controls keyboard focus order
readonly readOnly Makes a field read-only

Example

function LoginForm() {
  return (
    <form>
      <label htmlFor="email">Email Address</label>
      <input id="email" type="email" className="input-field" />
      <button type="submit">Login</button>
    </form>
  );
}

Remember: JSX attribute names are case-sensitive. Use the correct React-supported spelling.


6. Use Curly Braces to Embed JavaScript Expressions

Curly braces allow you to use JavaScript expressions inside JSX. Use them for variables, calculations, function calls, and dynamic attribute values.

Example

function Student() {
  const name = "Aarav";
  const marks = 85;

  return (
    <div>
      <h2>Student: {name}</h2>
      <p>Marks: {marks}</p>
      <p>Next score target: {marks + 10}</p>
    </div>
  );
}

Best practices

  • Use curly braces when inserting JavaScript expressions into JSX.
  • Keep expressions simple and easy to understand.
  • Move complicated calculations into variables or helper functions.
  • Remember that statements such as a standard if statement cannot be placed directly inside JSX braces; use them in the surrounding JavaScript code.

7. Keep JSX Expressions Simple

JSX should primarily describe the UI. Avoid putting complex calculations, deeply nested conditions, or long business logic directly inside markup.

Less readable

function Price({ price, discount }) {
  return (
    <p>
      Final Price: {price - (price * discount / 100) + (price * discount / 100 * 0.18)}
    </p>
  );
}

More readable

function Price({ price, discount }) {
  const discountedPrice = price - (price * discount / 100);
  const tax = discountedPrice * 0.18;
  const finalPrice = discountedPrice + tax;

  return (
    <p>Final Price: {finalPrice.toFixed(2)}</p>
  );
}

The second version separates the calculation from the presentation and is easier to test and maintain.


8. Break Large UI Sections into Reusable Components

Do not put an entire application's UI into one large component. Divide the interface into smaller components, each responsible for a clear task.

Example

function Header() {
  return <header><h1>My Website</h1></header>;
}

function MainContent() {
  return <main><p>Welcome to the website.</p></main>;
}

function Footer() {
  return <footer><p>Copyright 2026</p></footer>;
}

function App() {
  return (
    <>
      <Header />
      <MainContent />
      <Footer />
    </>
  );
}

export default App;

Advantages

  • Improves code readability.
  • Encourages reuse across pages.
  • Makes testing and debugging easier.
  • Allows components to be maintained independently.
  • Helps teams collaborate on different UI sections.

9. Use Props to Make Components Reusable

Props let a parent component pass information to a child component. Use props instead of duplicating nearly identical JSX for different content.

Example

function CourseCard({ title, duration }) {
  return (
    <article className="course-card">
      <h2>{title}</h2>
      <p>Duration: {duration}</p>
    </article>
  );
}

function App() {
  return (
    <div>
      <CourseCard title="React JS" duration="8 weeks" />
      <CourseCard title="JavaScript" duration="6 weeks" />
    </div>
  );
}

Best practice: Treat props as read-only. If a component needs to change information over time, use state or request an update through a callback provided by its parent.


10. Use Stable, Unique Keys When Rendering Lists

When you use map() to render multiple JSX elements, assign each sibling element a stable key. React uses keys to identify items as lists change.

Incorrect

const courses = ["React", "JavaScript", "CSS"];

function CourseList() {
  return (
    <ul>
      {courses.map(course => (
        <li>{course}</li>
      ))}
    </ul>
  );
}

Correct

const courses = [
  { id: 101, name: "React" },
  { id: 102, name: "JavaScript" },
  { id: 103, name: "CSS" }
];

function CourseList() {
  return (
    <ul>
      {courses.map(course => (
        <li key={course.id}>{course.name}</li>
      ))}
    </ul>
  );
}

Key rules

  • Use a stable identifier, such as a database ID, when available.
  • Keys must be unique among siblings in the same list.
  • Avoid array indexes as keys when items can be reordered, inserted, or removed.
  • Do not generate keys using Math.random() during rendering.
  • The key prop is used by React and is not passed to the component as an ordinary prop.

11. Use Conditional Rendering Carefully

React supports conditional rendering with JavaScript techniques such as if, the ternary operator, and logical AND (&&).

Using a ternary operator

function LoginStatus({ isLoggedIn }) {
  return (
    <p>
      {isLoggedIn ? "Welcome back!" : "Please log in."}
    </p>
  );
}

Using logical AND

function Notification({ messageCount }) {
  return (
    <div>
      {messageCount > 0 && (
        <p>You have new messages.</p>
      )}
    </div>
  );
}

Best practices

  • Use ternary expressions for simple either-or decisions.
  • Use && when content should appear only when a condition is true.
  • Use an if statement before the return when the logic is more complex.
  • Avoid deeply nested ternary expressions.
  • Be careful with numeric conditions: {messageCount && ...} may display 0 when the count is zero. Prefer {messageCount > 0 && ...}.

12. Use Semantic HTML Elements

Choose HTML elements according to their meaning and purpose instead of using generic div elements for everything. Semantic HTML improves accessibility, maintainability, and document structure.

Element Typical purpose
Introductory content or a page header
Navigation links
Main content of the page
A thematic section of content
Self-contained content
An action a user can trigger
Footer content

Example

function Dashboard() {
  return (
    <div>
      <header>
        <h1>Student Dashboard</h1>
      </header>
      <main>
        <section aria-labelledby="courses-heading">
          <h2 id="courses-heading">My Courses</h2>
          <p>View your enrolled courses here.</p>
        </section>
      </main>
    </div>
  );
}

13. Follow Accessibility Best Practices

Accessible JSX helps people use your application with keyboards, screen readers, and assistive technologies.

  • Use meaningful alternative text for informative images.
  • Associate form labels with inputs using htmlFor and matching input id values.
  • Use buttons for actions and links for navigation.
  • Ensure interactive controls can be operated with a keyboard.
  • Use appropriate headings and semantic HTML elements.
  • Do not rely on color alone to communicate important information.

Example

function SearchForm() {
  return (
    <form>
      <label htmlFor="search">Search courses</label>
      <input id="search" name="search" type="search" />
      <button type="submit">Search</button>
    </form>
  );
}

14. Use Event Handlers Correctly

In JSX, event handlers use camelCase names such as onClick and onChange. Pass a function to the event handler rather than calling it immediately during rendering.

Incorrect

<button onClick={handleClick()}>Click Me</button>

This calls handleClick while rendering, rather than waiting for a click, unless the function is intentionally designed to return an event handler.

Correct

function ActionButton() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

You can also pass an inline arrow function when you need to provide arguments:

<button onClick={() => handleSelect("React")}>
  Select React
</button>

15. Keep Components Pure and Avoid Side Effects During Rendering

A component should calculate its JSX from its props, state, and other inputs without unexpectedly changing external values during rendering. Rendering may happen more than once, so side effects should not be performed directly in the component body.

Incorrect

let totalVisitors = 0;

function VisitorCounter() {
  totalVisitors += 1;

  return <p>Visitors: {totalVisitors}</p>;
}

Better

function VisitorCounter({ totalVisitors }) {
  return <p>Visitors: {totalVisitors}</p>;
}

Pass values through props or manage changing data with React state. Use event handlers for user-triggered actions and effects for synchronization with external systems when appropriate.


16. Do Not Mutate Props or State Directly

Props and state should be treated as immutable values. Create a new array or object when updating state instead of modifying the existing value.

Incorrect state update

items.push("New Item");
setItems(items);

Correct state update

setItems(previousItems => [
  ...previousItems,
  "New Item"
]);

This example assumes items is state managed by a setter named setItems. Creating a new array allows React to detect the updated state correctly.


17. Use Consistent Styling Approaches

Choose a styling approach that fits the project and apply it consistently. JSX supports the className attribute for CSS classes and the style prop for inline style objects.

Using CSS classes

function PrimaryButton() {
  return (
    <button className="primary-button">
      Submit
    </button>
  );
}

Using inline styles

function Notice() {
  const noticeStyle = {
    color: "darkgreen",
    backgroundColor: "lightyellow",
    padding: "12px"
  };

  return (
    <p style={noticeStyle}>
      Your changes have been saved.
    </p>
  );
}

Best practice: Prefer CSS classes for reusable styling. Inline styles are useful for simple, dynamic values, but they are JavaScript objects and their property names use camelCase.


18. Avoid Unnecessary Nesting and Wrapper Elements

Excessive nesting makes JSX harder to read and maintain. Use the simplest structure that accurately represents the interface.

Too many wrappers

function Title() {
  return (
    <div>
      <div>
        <div>
          <h1>React Training</h1>
        </div>
      </div>
    </div>
  );
}

Simpler structure

function Title() {
  return (
    <header>
      <h1>React Training</h1>
    </header>
  );
}

Remove wrappers that do not serve a semantic, styling, layout, or functional purpose.


19. Use Self-Closing Tags Correctly

JSX requires tags without children to be self-closing. This is especially important for elements such as images and inputs.

Correct examples

<img src="/images/react-logo.png" alt="React logo" />
<input type="text" name="username" />
<CourseCard title="React JS" />

Elements with children should have matching opening and closing tags:

<button type="button">
  Learn More
</button>

20. Avoid Unsafe HTML Injection

React escapes ordinary text values rendered in JSX. Avoid using dangerouslySetInnerHTML unless you have a specific need to insert HTML markup and have properly sanitized the content.

Recommended for ordinary text

function Message({ text }) {
  return <p>{text}</p>;
}

When HTML is inserted directly, untrusted content can create cross-site scripting (XSS) risks. If rich HTML is required, sanitize it with a trusted sanitizer and carefully control the source.


21. Use Tools to Maintain JSX Quality

Development tools help detect syntax mistakes, inconsistent formatting, accessibility issues, and common React errors.

  • ESLint: Identifies code-quality issues and common mistakes.
  • React ESLint rules: Help detect React-specific problems, including hook-rule violations when configured.
  • Prettier: Automatically formats JSX and JavaScript consistently.
  • Browser developer tools: Help inspect errors, warnings, and UI behavior.
  • React Developer Tools: Helps inspect the component tree, props, and state.
  • Automated tests: Help verify component behavior and user interactions.

22. Complete Practical Example: Applying JSX Best Practices

This example combines readable formatting, reusable components, props, stable keys, semantic HTML, and accessible controls.

const courses = [
  { id: 1, title: "React JS", duration: "8 weeks" },
  { id: 2, title: "JavaScript", duration: "6 weeks" },
  { id: 3, title: "HTML and CSS", duration: "4 weeks" }
];

function CourseCard({ title, duration }) {
  return (
    <article className="course-card">
      <h3>{title}</h3>
      <p>Duration: {duration}</p>
      <button type="button">
        View Course
      </button>
    </article>
  );
}

function CourseList() {
  return (
    <section aria-labelledby="course-heading">
      <h2 id="course-heading">Available Courses</h2>
      <div className="course-list">
        {courses.map(course => (
          <CourseCard
            key={course.id}
            title={course.title}
            duration={course.duration}
          />
        ))}
      </div>
    </section>
  );
}

export default function App() {
  return (
    <main>
      <header>
        <h1>Welcome to Our Learning Platform</h1>
        <p>Choose a course to begin learning.</p>
      </header>
      <CourseList />
    </main>
  );
}

Best practices used in this example

  • Components use meaningful PascalCase names.
  • JSX is formatted with consistent indentation.
  • Course data is stored separately from the markup.
  • A reusable CourseCard component receives props.
  • Each list item has a stable, unique key.
  • Semantic elements describe the page structure.
  • Buttons specify their type.
  • The component structure is easy to extend and maintain.

23. Common JSX Mistakes and Their Solutions

Mistake Correct approach
Using class in JSX Use className.
Using lowercase custom component names Use PascalCase, such as UserCard.
Returning sibling elements without a wrapper Use a parent element or Fragment.
Rendering mapped elements without keys Provide stable keys unique among siblings.
Writing complex logic inside markup Move logic into variables or helper functions.
Calling an event handler during rendering Pass the function, such as onClick={handleClick}.
Using an incorrect HTML label attribute Use htmlFor in JSX.
Mutating state directly Create a new array or object and update state with its setter.
Using a number directly as a conditional AND check Use a boolean condition, such as count > 0.
Using unsafe HTML injection for ordinary text Render text normally inside JSX.

24. JSX Best Practices Checklist

  • Use consistent indentation and formatting.
  • Use meaningful component names in PascalCase.
  • Use one parent element or a Fragment for sibling elements.
  • Use correct JSX attributes, such as className and htmlFor.
  • Use curly braces for JavaScript expressions.
  • Keep JSX expressions simple and readable.
  • Split large interfaces into reusable components.
  • Pass data through props and treat props as read-only.
  • Provide stable keys when rendering lists.
  • Keep conditional rendering easy to understand.
  • Use semantic HTML and accessible form controls.
  • Pass event-handler functions correctly.
  • Avoid side effects during rendering.
  • Do not mutate props or state directly.
  • Use consistent styling conventions.
  • Avoid unnecessary wrappers and deep nesting.
  • Use self-closing syntax for elements without children.
  • Avoid unsafe HTML injection.
  • Use linting, formatting, and testing tools.

25. Interview Questions and Answers

Q1. What are JSX best practices?

Answer: JSX best practices are coding guidelines that help developers create readable, maintainable, accessible, reusable, and reliable React interfaces.

Q2. Why should component names start with an uppercase letter?

Answer: React uses uppercase names to identify custom components. Lowercase names are interpreted as built-in HTML tags.

Q3. Why do we use className instead of class?

Answer: JSX uses the JavaScript-oriented attribute name className to assign CSS classes.

Q4. Why are keys important in React lists?

Answer: Keys help React identify list items across updates, insertions, deletions, and reordering.

Q5. What is the benefit of using React Fragments?

Answer: Fragments group multiple JSX elements without adding an unnecessary DOM wrapper.

Q6. Why should components be small and reusable?

Answer: Smaller components are easier to understand, test, debug, reuse, and maintain.

Q7. What is the difference between props and state?

Answer: Props are inputs passed to a component, usually by its parent. State is data managed by a component or its state-management logic that can change over time.

Q8. Why should state not be mutated directly?

Answer: Direct mutation can prevent React from detecting updates correctly and can lead to unpredictable UI behavior. Use state setters and create updated values instead.

Q9. Why is semantic HTML important in JSX?

Answer: Semantic HTML communicates the meaning of content and improves accessibility and maintainability.

Q10. How can developers maintain consistent JSX formatting?

Answer: They can use a consistent style guide and automatic formatting tools such as Prettier, together with ESLint for code-quality checks.


26. Conclusion

Following JSX best practices helps developers build React applications that are readable, accessible, reusable, and easier to maintain. Focus on clean formatting, meaningful components, simple expressions, stable list keys, correct attributes, semantic HTML, safe event handling, and immutable state updates.

For more structured learning, visit the JustAcademy React JS Training Course or register for a React JS course demo.

Official React Documentation

whatsapp